<?php

namespace app\stores\controller\miniapp\order;

use app\BaseController;

use app\beautiful\logic\LogsLogic;
use app\beautiful\model\mall\FlashSaleGoodsModel;
use app\common\model\CustomerServiceModel;
use app\stores\logic\MemberWalletLogic;
use app\beautiful\logic\PartnerLogic;
use app\beautiful\logic\printer\PrinterLogic;
use app\beautiful\model\goods\GoodsOtherSkuDetailModel;
use app\beautiful\model\mall\GoodsModel;
use app\beautiful\model\goods\GoodsWriteOffModel;
use app\beautiful\model\mall\PinTuanGroupModel;
use app\beautiful\model\member\MemberCouponModel;
use app\beautiful\model\order\GoodsOrderItemModel;
use app\beautiful\model\order\OrderGoodsGroupDetailModel;
use app\beautiful\model\order\OrderGoodsGroupModel;
use app\beautiful\model\order\OrderGoodsModel;
use app\beautiful\model\order\OrderRefundModel;
use app\beautiful\model\setting\SettingSmsModel;
use app\common\logic\DataLogic;
use app\common\logic\SmsLogic;
use app\common\model\ShopModel;
use app\stores\logic\order\OrderLogic;
use app\stores\model\order\ChargebackModel;
use app\stores\model\order\GoodsOrderModel;
use app\stores\model\promotion\ActivityModel;
use app\stores\model\promotion\TeamActivityModel;
use think\facade\Db;


class Order extends BaseController{
    /**
     * 订单中心订单列
     */
    public function getGoodsOrderList(){
        $lng =  $this->request->param('lng/f',0);
        $lat =  $this->request->param('lat/f',0);
        $status = $this->request->param('status/d');//0全部
        $where= [
            ['member_id','=', $this->request->memberId],
            ['is_delete','=',0],
            ['from_type','=',2],
            ['order_type','<>','pin_tuan']
        ];

        switch ($status){ //查询订单的状态
            case 1://待使用
                $where[] = ['status','=',10];
                break;
            case 2: // 待付款
                $where[] = ['status','=',1];
                break;
            case 3: //待收货
                $where[] = ['status','=',3];
                break;
            case 4://待自提
                $where[] = ['status','=',4];
                break;
            case 5://退款
                $where[] = ['status','IN',[11,12]];
                break;
            case 6://待分配
                $where[] = ['status','=',9];
                break;

        }
        //存在的门店
        $shop_ids = ShopModel::where(['open_status'=>1])->column('shop_id');
        $where[] = ['shop_id','In',$shop_ids];

        $order = ['order_id'=>'desc'];

        $goodsModel = GoodsOrderModel::with(['skus','shop'=>function($query){

            $query->with(['detail'=>function($query){

                $query->field('shop_id,lat,lng,tel,address,logo');

            }])->field('shop_id,name');

        }])->json(['discount_detail'],true);


        $field = "order_id,order_type,logistics_type,total_price,is_paid,pay_time,status,add_time,order_send_time,receiving_name,receiving_mobile,receiving_address_province,receiving_address_city,receiving_address_county,receiving_address_info,order_send_time";

        $append = ['pay_time','add_time','djs_time'];

        $return = DataLogic::getDataList($goodsModel,$where,$order,$field,$this->request->limit,$this->request->page,$append);

        $list = $return['list'];
        foreach ($list as $k=>$v){
            $distance = 0;
            if($v['logistics_type']==3){
                $distance = get_distance($lat,$lng,$v['shop']['detail']['lat'],$v['shop']['detail']['lng']);
            }
            $list[$k]['shop'] = [
                'name'=>$v['shop']['name'],
                'logo'=>$v['shop']['detail']['logo'],
                'shop_id'=>$v['shop']['detail']['shop_id'],
                'tel'=>$v['shop']['detail']['tel'],
                'address'=>$v['shop']['detail']['address'],
                'distance'=>$distance,
                'lat'=>$v['shop']['detail']['lat'],
                'lng'=>$v['shop']['detail']['lng'],
            ];
            $list[$k]['order_send_time'] = $v['order_send_time']?json_decode($v['order_send_time'],true):$v['order_send_time'];
            $order_data = OrderGoodsModel::where(['order_id'=>$v['order_id']])->find();
            foreach ($v['skus'] as $kk=>$vv){
                $start_time = $end_time = null;
                if($vv['type'] == 3 && $v['is_paid'] == 1){
                    $order_data->pay_time = strtotime($v['pay_time']);
                    $time = $this->getTime($order_data,$vv);
                    $start_time = $time->start_time;
                    $end_time = $time->end_time;
                }
                $v['skus'][$kk]['start_time'] = $start_time;
                $v['skus'][$kk]['end_time'] = $end_time;
                if($v['activity_title']) $v['skus'][$kk]['goods_name'] = $v['activity_title'];
                
            }
            $list[$k]['skus'] = $v['skus'];
        }
        $return['list'] = $list;
        return $this->success($return);
    }

    private function getTime($order_data,$item){
        $order_goods = OrderGoodsModel::where(['order_item_id'=>$item['order_item_id'],'order_id'=>$item['order_id']])->find();
        $order_goods = goodsEndTime($order_goods,$order_data);
        return $order_goods;
    }
    /**
     * 订单详情
     */
    public function orderDetail(){
        $order_id = $this->request->param('order_id/d',0);
        $type = $this->request->param('type/d',2);
        $lng =  $this->request->param('lng/f',0);
        $lat =  $this->request->param('lat/f',0);
        if(empty($order_id)) return $this->error('订单不存在');
        $where= [
            ['member_id','=', $this->request->memberId],
            ['is_delete','=',0],
            ['order_id','=',$order_id]
        ];

        $data = \app\beautiful\model\order\GoodsOrderModel::with(['skus'])->json(['order_send_time'],true)->where($where)->find();
        if(null === $data) return $this->error ('订单不存在');
        $datas = $data->append(['order_time','djs_time','youhui','pay_time_format','pay_type_mean'])
            ->toArray();

        if($datas['skus'][0]['type']==3){
            //套餐只有一个子订单
            $item = $datas['skus'][0];

            //拼团套餐
            if($data['order_type']=='pin_tuan'){
                $goods = OrderGoodsModel::where(['pin_tuan_order_id'=>$datas['pin_tuan_order_id']])->find();
                $goods_id =$goods->goods_id;
                $where = [
                    'is_delete'=>0,
                    'pin_tuan_order_id'=>$data['pin_tuan_order_id'],
                ];
            }else if($data['order_type']=='flash_sale'){
                $goods = OrderGoodsModel::where(['order_id'=>$order_id])->find();
                $goods_id =$goods->goods_id;
                $where = [
                    'is_delete'=>0,
                    'order_id'=>$order_id,
                    'order_item_id'=>$item['order_item_id'],
                ];
            }else{

                $goods_id = $item['goods_id'];
                $where = [
                    'is_delete'=>0,
                    'order_id'=>$order_id,
                    'order_item_id'=>$item['order_item_id'],
                ];
            }

            //分组与分组详情
            $group = OrderGoodsGroupModel::with(['orderGoodsGroupDetail'=>function($query){
                $query->where(['is_delete'=>0])->order(['sort'=>'desc']);
            }])->where($where)
                ->select()->toArray();
            //是否核销完
            $remain_num = 0;
            $is_many_hx= 0;
            foreach ($group as $k=>$v){
                $return = $this->orderGoodsGroupDetail($v['orderGoodsGroupDetail']);
                $remain_num += $return['remain_num'];
                $is_many_hx = $return['is_many_hx'];
                $group[$k]['orderGoodsGroupDetail'] = $return['orderGoodsGroupDetail'];
            }
            $item['group'] = $group;
                //套餐其他信息
            $goods = OrderGoodsModel::where(['goods_id'=>$goods_id])->where($where)->json(['use_limit_detail'],true)->find();

            $goods->goods_name = $datas['activity_title']?$datas['activity_title']:$item['goods_name'];
            $goods->goods_cover_img = $item['goods_cover_img'];
            $goods->original_price = $datas['activity_title']?$datas['activity_price']:$item['goods_original_price'];
            //到期时间
            $end_time = goodsEndTime($goods,$data);
            $goods->start_time = $end_time['start_time'];
            $goods->end_time = $end_time['end_time'];
            //是否核销完
//            $remain_num = 0;
//            $is_many_hx= 0;
//            $group_detail = OrderGoodsGroupDetailModel::where($where)->select()->toArray();
//            foreach ($group_detail as $k=>$v){
//                $remain_num += $v['remain_num'];
//                if($v['use_condition']!=1){
//                    $is_many_hx= 1;
//                }
//                $group_detail[$k]['total_goods_name'] = $v['goods_original_price'] * $v['num'];
//            }
            //使用情况
            $un_one_order_goods_group_detail_ids = OrderGoodsGroupDetailModel::where($where)->where('use_condition','<>',1)->column('order_goods_group_detail_id');
            $write_off = GoodsWriteOffModel::with(['orderGoodsGroupDetail'])->where(['order_id'=>$order_id])->select()->toArray();
            $write_offs = [];
            foreach ($write_off as $k=>$v){
                if(in_array($v['orderGoodsGroupDetail']['order_goods_group_detail_id'],$un_one_order_goods_group_detail_ids)){
                    $write_offs[$k] = $v;
                    $write_offs[$k]['goods_name'] = $v['orderGoodsGroupDetail']['goods_name'];
                    $write_offs[$k]['sku_name'] = $v['orderGoodsGroupDetail']['sku_name'];
                    $write_offs[$k]['unit'] = $v['orderGoodsGroupDetail']['unit'];
                }
                unset($write_off[$k]['orderGoodsGroupDetail']);
            }
            $all_once_write_off_time = (!$write_offs && !$un_one_order_goods_group_detail_ids && $write_off)?$write_off[0]['add_time']:null;

            //$datas['num'] = $data['status']==8?0:$item['goods_num'];
            $datas['num'] = $item['goods_num'];
            $datas['goods'] = $goods;
            $datas['item'] = $item;
            $datas['is_end'] = $remain_num<1?1:0;
            $datas['write_off'] = $write_offs;
            $datas['all_once_write_off_time'] = $all_once_write_off_time;
            $datas['remain_num'] = $remain_num;
            $datas['is_many_hx'] = $is_many_hx;
        }else{
            //产品有多个子订单
            //订单总数
            $num = 0;
            if($datas['skus']){
                $sku = $datas['skus'];
                foreach ($sku as $k=>$v){
                    $num +=$v['goods_num'];

                }
            }
            //$datas['num'] = $data['status']==8?0:$num;
            $datas['num'] = $num;
            $datas['goods'] = null;
            if($datas['order_type'] == 'flash_sale'){
                $order_goods = OrderGoodsModel::where(['order_id'=>$datas['order_id']])->field('start_time,end_time')->find();
                $datas['goods'] = $order_goods;
            }

        }
        //地推及时结算不能退款
        $settle_type = 2;
        if($datas['team_activity_id']){
            $team_activity = TeamActivityModel::where(['team_activity_id'=>$datas['team_activity_id'],'is_delete'=>0])->find();
            if($team_activity) {
                $activity = ActivityModel::where(['activity_id' => $team_activity->activity_id,'is_delete' => 0])->find();
                if($activity) $settle_type = $activity->settle_type;
            }
        }
        //退单信息
        $chargeback_list = ChargebackModel::getList(['order_id'=>$order_id],['add_time'=>'asc'],'c.add_time,c.num,c.reason,i.goods_name,i.goods_sku_name,d.group_detail_name');
        //退款信息
        $order_refund_list = OrderRefundModel::where(['order_id'=>$order_id,'is_delete'=>0])->field('update_time,refund_price,refund_type,reason,remarks,status')->select()->toArray();
        //门店(不管下架和删除)
        $shop = ShopModel::with(['detail'])->where(['shop_id'=>$datas['shop_id']])->field('shop_id,name,customer_service_id')->find();
        $service = CustomerServiceModel::where(['customer_service_id'=>$shop->customer_service_id])->find();
        if($datas['refund_money']>0){
            $refund_status = $datas['refund_money']<$datas['need_pay']?2:1;
        }else{
            $refund_status = 0;
        }

        $datas['shop_name'] = $shop->name;
        $datas['shop_logo'] = $shop->detail->logo;
        $datas['shop_address'] = $shop->detail->address;
        $datas['shop_tel'] = $service?$service->mobile:null;
        $datas['shop_distance'] = get_distance($lat,$lng,$shop->detail->t_lat,$shop->detail->t_lng);
        $datas['shop_lat'] = $shop->detail->t_lat;
        $datas['shop_lng'] = $shop->detail->t_lng;
        $datas['settle_type'] = $settle_type;
        $datas['chargeback_list'] = $chargeback_list;
        $datas['order_refund_list'] = $order_refund_list;
        $datas['refund_status'] = $refund_status;
        return $this->success($datas);
    }
    protected function orderGoodsGroupDetail($orderGoodsGroupDetail){
        $remain_num = 0;
        $is_many_hx = 0;
        foreach ($orderGoodsGroupDetail as $k=>$v){
            $remain_num += $v['remain_num'];
            if($v['use_condition']!=1){
                $is_many_hx= 1;
            }
            $orderGoodsGroupDetail[$k]['total_goods_price'] = $v['goods_original_price']*$v['num'];
        }
        $return['is_many_hx'] = $is_many_hx;
        $return['remain_num'] = $remain_num;
        $return['orderGoodsGroupDetail'] = $orderGoodsGroupDetail;
        return $return;
    }

    /**
     * 通用门店列表(不管下架和删除)
     */
    public function generalShopList(){
        $goods_id = $this->request->param('goods_id/d',0);
        $lng =  $this->request->param('lng/f',0);
        $lat =  $this->request->param('lat/f',0);
        if($goods_id<1) return $this->error('参数有误');
        $goods = GoodsModel::where(['goods_id'=>$goods_id])->find();
        $general_shop_ids = explode(',',$goods->general_shop);
        $general_shop_ids[] = $goods->shop_id;
        $general_shop_list = $this->generalShops($general_shop_ids,$lat,$lng);

        return  $this->success($general_shop_list);
    }
    //通用门店
    protected function generalShops($general_shop_ids,$lat,$lng){
        $general_shop_list = ShopModel::with(['detail'])->whereIn('shop_id',$general_shop_ids)->field('shop_id,name')->select()->toArray();
       
        foreach ($general_shop_list as $k=>$v){
            $general_shop_list[$k] = $this->generalShop($v);
            $general_shop_list[$k]['distance'] = get_distance($lat,$lng,$v['detail']['t_lat'],$v['detail']['t_lng']);
        }

        return $general_shop_list;
    }
    //通用门店信息
    protected function generalShop($generalShop){
        $generalShop['tel'] = $generalShop['detail']['tel'];
        $generalShop['address'] = $generalShop['detail']['address'];
        $generalShop['logo'] = $generalShop['detail']['logo'];
        $generalShop['lat'] = $generalShop['detail']['lat'];
        $generalShop['lng'] = $generalShop['detail']['lng'];

        unset($generalShop['imglst']);
        unset($generalShop['detail']);

        return $generalShop;
    }
    public function cancelOrder()
    {
        $order_id=$this->request->param('order_id/d',0);
        if(empty($order_id)) return $this->error('订单不存在');
        $params=[
            'member_id'=>$this->request->memberId,
            'order_id'=>$order_id,
        ];

        $order= \app\beautiful\model\order\GoodsOrderModel::find($order_id);
        if(null === $order) $this->error('订单不存在');
        Db::startTrans();
        try{
            $order_logic = OrderLogic::init($this->request->shopId);
            $order_logic[$order->order_type]->cancelOrder($params);
            Db::commit();
            return $this->success('成功');
        } catch (\Exception $e){
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }
    /**
     * 订单退款申请页面
     */
    public function applyForRefund(){
        $order_id = $this->request->param('order_id/d',0);
        $where= [
            ['member_id','=', $this->request->memberId],
            ['is_delete','=',0],
            ['order_id','=',$order_id]
        ];
        $data = \app\beautiful\model\order\GoodsOrderModel::with(['skus'])->json(['order_send_time'],true)->where($where)->find();
        if(null === $data) return $this->error ('订单不存在');
        $datas = $data->append(['order_time','djs_time','youhui','pay_time_format','pay_type_mean'])
                    ->toArray();

        $datas['coupon_name'] = null;
        if($datas['member_coupon_id']){
            $member_coupon = MemberCouponModel::where(['member_coupon_id'=>$datas['member_coupon_id']])->find();
            $datas['coupon_name'] = $member_coupon->name;

        }

        if(!in_array($datas['status'],[2,3,4,9,10]) ) return $this->error ('该订单不能退款');

        //地推及时结算不能退款
        if($datas['team_activity_id']){
            $team_activity = TeamActivityModel::where(['team_activity_id'=>$datas['team_activity_id'],'is_delete'=>0])->find();
            if($team_activity) {
                $activity = ActivityModel::where(['activity_id' => $team_activity->activity_id,'is_delete' => 0])->find();
                if($activity->settle_type==1){
                    return $this->error ('特价活动套餐一经售出不支持退款');
                }
            }
        }

        $write_off = GoodsWriteOffModel::with(['orderGoodsGroupDetail'])->where(['order_id'=>$order_id])->select()->toArray();
        if($write_off) return $this->error ('该订单有核销数据不能退款');

        $item = $datas['skus'];

        foreach ($item as $k=>$v){
            if($v['type'] == 3){
                $where_g = [
                    ['is_delete','=',0],
                ];
                if($datas['order_type'] == 'pin_tuan'){
                    $where_g [] = ['pin_tuan_order_id','=',$datas['pin_tuan_order_id']];
                }else{
                    //秒杀订单子订单goods_id存的秒杀id
                    if($datas['order_type'] == 'flash_sale'){
                        $flash_sale_goods = FlashSaleGoodsModel::where(['flash_sale_goods_id'=>$v['goods_id']])->find();
                        $v['goods_id'] = $flash_sale_goods['goods_id'];
                    }
                    $where_g [] = ['order_id','=',$order_id];
                    $where_g [] = ['goods_id','=',$v['goods_id']];
                    $where_g [] = ['order_item_id','=',$v['order_item_id']];
                }

                $order_goods = OrderGoodsModel::where($where_g)->json(['use_limit_detail'],true)->find();

                $item[$k]['use_limit_detail'] = $order_goods->use_limit_detail;
                $item[$k]['is_need_appointment'] = $order_goods->is_need_appointment;
                $item[$k]['appointment_explain'] = $order_goods->appointment_explain;
                $item[$k]['use_limit'] = $order_goods->use_limit;
            }
        }


        $datas['skus'] = $item;
        return $this->success($datas);


    }
    /**
     * 订单退款申请
     * */
    public function refund(){
        $order_id = $this->request->param('order_id/d',0);
        $remarks = $this->request->param('remarks');
        $where= [
            ['member_id','=', $this->request->memberId],
            ['is_delete','=',0],
            ['order_id','=',$order_id]
        ];
        $datas = \app\beautiful\model\order\GoodsOrderModel::where($where)->json(['order_send_time'],true)->find();
        if(null === $datas) return $this->error ('订单不存在');

        if(!in_array($datas->status,[2,3,4,9,10]) ) return $this->error ('该订单不能退款');

        //地推及时结算不能退款
        if($datas->team_activity_id){
            $team_activity = TeamActivityModel::where(['team_activity_id'=>$datas->team_activity_id,'is_delete'=>0])->find();
            if($team_activity) {
                $activity = ActivityModel::where(['activity_id' => $team_activity->activity_id,'is_delete' => 0])->find();
                if($activity->settle_type==1){
                    return $this->error ('特价活动套餐一经售出不支持退款');
                }
            }
        }

        $write_off = GoodsWriteOffModel::with(['orderGoodsGroupDetail'])->where(['order_id'=>$order_id])->select()->toArray();
        if($write_off) return $this->error ('该订单有核销数据不能退款');

        Db::startTrans();

        try{
            //退款记录
            $total_refund_platform_money = OrderRefundModel::where(['order_id'=>$order_id,'is_delete'=>0])->where('status','>=',0)->sum('refund_platform_money');
            $total_refund_money = OrderRefundModel::where(['order_id'=>$order_id,'is_delete'=>0])->where('status','>=',0)->sum('refund_money');
            $total_refund_weixin = OrderRefundModel::where(['order_id'=>$order_id,'is_delete'=>0])->where('status','>=',0)->sum('refund_weixin');
            $refund = new OrderRefundModel();
            $refund->shop_id = $datas->shop_id;
            $refund->order_id = $order_id;
            $refund->member_id = $datas->member_id;
            $refund->refund_price = $datas->need_pay - $datas->refund_money;
            $refund->refund_platform_money = $datas->platform_money - $total_refund_platform_money;
            $refund->refund_money = $datas->money - $total_refund_money;
            $refund->refund_weixin = $datas->weixin - $total_refund_weixin;
            $refund->remarks = $remarks;
            $refund->save();

            $update_data['status'] = 11;
            $update_data['edit_time'] = date('Y-m-d H:i:s');
            GoodsOrderModel::where(['order_id'=>$order_id])->save($update_data);
            Db::commit();

        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }
        return $this->success('提交成功');
    }
    /**
     * 商城使用余额支付订单
     * */
    public function getGoodsOrderMoneyPay(){
        $order_id = $this->request->param('order_id/d');
        $mix_pay_type = $this->request->param('mix_pay_type');
        if(empty($order_id)){
            return $this->error('请选择要支付的订单');
        }
        if( null === $order = \app\beautiful\model\order\GoodsOrderModel::find($order_id)){
            return $this->error('订单不存在');
        }
        if($order->status != 1 || $order->is_delete == 1){
            return $this->error('订单不在未支付状态');
        }
        $time = time() - 1800;//订单30分钟
        if($order->add_time < $time){ //如果 订单超过30分钟则不能支付了
            return $this->error('订单支付已经超时了，不能继续支付');
        }
        if($order->shop_id != $this->request->shopId || $order->member_id != $this->request->memberId){
            return $this->error('订单不存在');
        }
        Db::startTrans();
        try{
            //待付款选择混合支付修改订单
            if($mix_pay_type){
                //判断支付方式
                $params['mix_pay_type'] = $mix_pay_type;
                $return = checkPayWay($params,$order->need_pay,$this->request->memberId,$this->request->shopId);
                if($return['error']){
                    return $this->error($return['error']);
                }else{
                    $mix_pay_money = $return['mix_pay_money'];
                    $mix_pay_type=(isset($mix_pay_money) && $mix_pay_money)?implode(',',array_keys($mix_pay_money)):null;
                    $platform_money = isset($mix_pay_money['platform_money'])?$mix_pay_money['platform_money']:0;
                    $money = isset($mix_pay_money['money'])?$mix_pay_money['money']:0;
                    $weixin = isset($mix_pay_money['weixin'])?$mix_pay_money['weixin']:0;
                }
            }else{
                $mix_pay_type = null;
                $platform_money = $money = $weixin = 0;
            }
            $order->mix_pay_type = $mix_pay_type;
            $order->platform_money = $platform_money;
            $order->money = $money;
            $order->weixin = $weixin;
            $order->save();
            $order = \app\beautiful\model\order\GoodsOrderModel::find($order_id);

            if(!empty($order->member_coupon_id)){
                if(null === $myCoupon = MemberCouponModel::find($order->member_coupon_id)){
                    Db::rollback();
                    return $this->error('优惠券不存在');
                }
                if($myCoupon->status == 1){
                    Db::rollback();
                    return $this->error('优惠券不存在');
                }
                $myCoupon->status = 1;
                $myCoupon->save();
                LogsLogic::coupon($this->request->shopId, $this->request->memberId, -1, 12, $order->member_coupon_id, '', 0);
            }
            $MemberWalletLogic = new MemberWalletLogic($this->request->shopId, $this->request->memberId);
            if(!empty($order->use_integral)){ //使用积分
                $res = $MemberWalletLogic->useIntegral($order->use_integral, 9);
                if($res == false){
                    Db::rollback();
                    return $this->error($MemberWalletLogic->getError());
                }
            }
            $needPay = round(($order->total_price * 100 + $order->freight * 100 - $order->coupon_money * 100 - $order->integral_balance * 100)/100,2);
            if($needPay <= 0){
                Db::rollback();
                $this->error('支付金额不正确');
            }
            if(!empty($mix_pay_type)){
                $return = mix_pay_money($order,'',2);
                if($return['error']){
                    Db::rollback();
                    return $this->error($return['error']);
                }
            }else {
                $res = $MemberWalletLogic->useBalance($needPay, $order->total_price + $order->freight, 8); //商城购物使用
                if ($res == false) {
                    Db::rollback();
                    return $this->error($MemberWalletLogic->getError());
                }
            }
            $order->is_paid = 1;
            $order->pay_time = time();
            $order->edit_time = date('Y-m-d H:i:s');

            $order->status = $order->logistics_type == 1? 2 : 4; //订单的状态值

            if($order->logistics_type == 3) $order->status = 9;

            //根据子订单判断类型
            $item_order = GoodsOrderItemModel::where(['order_id'=>$order_id])->find();

            if($order->order_type == 'set_meal' || ($order->order_type == 'flash_sale' && $item_order->type == 3)) $order->status = 10;

            $order->pay_type = 'money';
            $order->verify_code = getVerifyCode($order_id);
            if(empty($mix_pay_type)) $order->money = $order->need_pay;
            $order->save();

            //修改套餐有效期
            if($order->order_type == 'set_meal' || ($order->order_type == 'flash_sale' && $item_order->type == 3)){
                $order_goods = OrderGoodsModel::where(['order_id'=>$order_id,'is_delete'=>0])->find();
                if($order_goods && $order_goods->use_type!=1){
                    $end_time = goodsEndTime($order_goods,$order);
                    $order_goods->start = $end_time->start_time;
                    $order_goods->end = $end_time->end_time;
                    $order_goods->save();
                }


            }

            //发送短信给管理员
            try{
                $sms_setting = SettingSmsModel::where([['shop_id','=',$this->request->shopId]])->find();
                if(null !== $sms_setting){
                    if($sms_setting->order_notice_admin==1){
                        $sms_logic= new SmsLogic();
                        $params=[
                            'money'=>$needPay,
                        ];

                        $sms_logic->send($this->request->shopId,$sms_setting->boss_mobiles,$params,'orderNoticeAdmin');
                    }
                }
            }catch (\Exception $e){

            }
            //单店版下单支付就分红，多店版收货后订单完成才分红
            if($order->from_type == 1){
                //分红
                $PartnerLogic = new PartnerLogic($order->shop_id);

                $PartnerLogic->commissionNew($order->member_id,$needPay,'order',$order_id);
            }
            //地推分红
            if($order->p_mid>0){
                promotion_money($order->team_activity_id,$order_id,$item_order->goods_num,1);
            }
            //打印机
            if($order->logistics_type == 1){
                $type = 'kuaidi';
            }
            if($order->logistics_type == 2){
                $type = 'self';
            }
            if($order->logistics_type == 3){
                $type = 'city';
            }
            if(in_array($order->logistics_type,[1,2,3])){
                //判断是否有分区打印的产品
                $return_goods_produce = goodsProduce($order_id);
                $prints = $return_goods_produce['prints'];
                $produce_printer_ids = [];
                if($prints){
                    $printer_logic = new \app\stores\logic\printer\PrinterLogic($order->shop_id);
                    $produce_printer_ids = $printer_logic->producePrint($type,$order_id,$prints);
                }
                //原来的打印排除已分区打印的打印机
                $printer_logic = new PrinterLogic($order->shop_id);
                $printer_logic->print($type,$order_id,$produce_printer_ids);

            }


            Db::commit();
            return $this->success('储值卡支付成功');
        }catch(\Exception $e){
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }
    /**
     *使用钱包支付订单
     */
    public function getGoodsOrderPlatformMoneyPay(){
        $order_id = $this->request->param('order_id/d');
        $mix_pay_type = $this->request->param('mix_pay_type');
        if(empty($order_id)){
            return $this->error('请选择要支付的订单');
        }
        if( null === $order = \app\beautiful\model\order\GoodsOrderModel::find($order_id)){
            return $this->error('订单不存在');
        }
        if($order->status != 1 || $order->is_delete == 1){
            return $this->error('订单不在未支付状态');
        }
        $time = time() - 1800;//订单30分钟
        if($order->add_time < $time){ //如果 订单超过30分钟则不能支付了
            return $this->error('订单支付已经超时了，不能继续支付');
        }
        if($order->shop_id != $this->request->shopId || $order->member_id != $this->request->memberId){
            return $this->error('订单不存在');
        }

        Db::startTrans();
        try{
            //待付款选择混合支付修改订单
            if($mix_pay_type){
                //判断支付方式
                $params['mix_pay_type'] = $mix_pay_type;
                $return = checkPayWay($params,$order->need_pay,$this->request->memberId,$this->request->shopId);

                if($return['error']){
                    return $this->error($return['error']);
                }else{
                    $mix_pay_money = $return['mix_pay_money'];
                    $mix_pay_type=(isset($mix_pay_money) && $mix_pay_money)?implode(',',array_keys($mix_pay_money)):null;
                    $platform_money = isset($mix_pay_money['platform_money'])?$mix_pay_money['platform_money']:0;
                    $money = isset($mix_pay_money['money'])?$mix_pay_money['money']:0;
                    $weixin = isset($mix_pay_money['weixin'])?$mix_pay_money['weixin']:0;
                }
            }else{
                $mix_pay_type = null;
                $platform_money = $money = $weixin = 0;
            }
            $order->mix_pay_type = $mix_pay_type;
            $order->platform_money = $platform_money;
            $order->money = $money;
            $order->weixin = $weixin;
            $order->save();
            $order = \app\beautiful\model\order\GoodsOrderModel::find($order_id);

            if(!empty($order->member_coupon_id)){
                if(null === $myCoupon = MemberCouponModel::find($order->member_coupon_id)){
                    Db::rollback();
                    return $this->error('优惠券不存在');
                }
                if($myCoupon->status == 1){
                    Db::rollback();
                    return $this->error('优惠券不存在');
                }
                $myCoupon->status = 1;
                $myCoupon->save();
                LogsLogic::coupon($this->request->shopId, $this->request->memberId, -1, 12, $order->member_coupon_id, '', 0);
            }
            $MemberWalletLogic = new MemberWalletLogic($this->request->shopId, $this->request->memberId);
            if(!empty($order->use_integral)){ //使用积分
                $res = $MemberWalletLogic->useIntegral($order->use_integral, 9);
                if($res == false){
                    Db::rollback();
                    return $this->error($MemberWalletLogic->getError());
                }
            }
            $needPay = round(($order->total_price * 100 + $order->freight * 100 - $order->coupon_money * 100 - $order->integral_balance * 100)/100,2);
            if($needPay <= 0){
                Db::rollback();
                $this->error('支付金额不正确');
            }
            $order->is_paid = 1;
            $order->pay_time = time();
            $order->edit_time = date('Y-m-d H:i:s');
            $order->status = $order->logistics_type == 1? 2 : 4; //订单的状态值

            if($order->logistics_type == 3) $order->status = 9;

            $item_order = GoodsOrderItemModel::where(['order_id'=>$order_id])->find();

            if($order->order_type == 'set_meal' || ($order->order_type == 'flash_sale' && $item_order->type == 3)) $order->status = 10;

            $order->pay_type = 'platform_money';
            $order->verify_code = getVerifyCode($order_id);
            if(empty($mix_pay_type)) $order->platform_money = $order->need_pay;
            $order->save();

            if(!empty($mix_pay_type)){
                $return = mix_pay_money($order,'',2);
                if($return['error']){
                    Db::rollback();
                    return $this->error($return['error']);
                }
            }else{
                $StoresMemberWalletLogic = new \app\stores\logic\MemberWalletLogic($this->request->shopId, $this->request->memberId);
                $type = $order->order_type == 'flash_sale'?7:1;
                $res = $StoresMemberWalletLogic->usePlatformMoney($needPay, 0 , $order->order_id,0,$type); //商城购物使用
                if($res == false){
                    Db::rollback();
                    return $this->error($MemberWalletLogic->getError());
                }
            }
            //修改套餐有效期
            if($order->order_type == 'set_meal'){
                $order_goods = OrderGoodsModel::where(['order_id'=>$order_id,'is_delete'=>0])->find();
                if($order_goods && $order_goods->use_type!=1){
                    $end_time = goodsEndTime($order_goods,$order);
                    $order_goods->start = $end_time->start_time;
                    $order_goods->end = $end_time->end_time;
                    $order_goods->save();
                }


            }
            //发送短信给管理员
            try{
                $sms_setting = SettingSmsModel::where([['shop_id','=',$this->request->shopId]])->find();
                if(null !== $sms_setting){
                    if($sms_setting->order_notice_admin==1){
                        $sms_logic= new SmsLogic();
                        $params=[
                            'money'=>$needPay,
                        ];
                        $sms_logic->send($this->request->shopId,$sms_setting->boss_mobiles,$params,'orderNoticeAdmin');
                    }
                }
            }catch (\Exception $e){

            }
            //单店版下单支付就分红，多店版收货后订单完成才分红
            if($order->from_type == 1){
                //分红
                $PartnerLogic = new PartnerLogic($order->shop_id);

                $PartnerLogic->commissionNew($order->member_id,$needPay,'order',$order_id);
            }
            //地推分红
            if($order->p_mid>0){
                promotion_money($order->team_activity_id,$order_id,$item_order->goods_num,1);
            }
            //打印机
            if($order->logistics_type == 1){
                $type = 'kuaidi';
            }
            if($order->logistics_type == 2){
                $type = 'self';
            }
            if($order->logistics_type == 3){
                $type = 'city';
            }
            if(in_array($order->logistics_type,[1,2,3])){
                //判断是否有分区打印的产品
                $return_goods_produce = goodsProduce($order_id);
                $prints = $return_goods_produce['prints'];
                $produce_printer_ids = [];
                if($prints){
                    $printer_logic = new \app\stores\logic\printer\PrinterLogic($order->shop_id);
                    $produce_printer_ids = $printer_logic->producePrint($type,$order_id,$prints);
                }
                //原来的打印排除已分区打印的打印机
                $printer_logic = new PrinterLogic($order->shop_id);
                $printer_logic->print($type,$order_id,$produce_printer_ids);

            }

            Db::commit();
            return $this->success('余额支付成功');
        }catch(\Exception $e){
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }

    /**
     * 确定收货
     */
    public function yesOrder(){
        $order_id=$this->request->param('order_id/d',0);
        if(empty($order_id)) return $this->error('订单不存在');
        $order= \app\beautiful\model\order\GoodsOrderModel::find($order_id);
        if(null === $order) return $this->error ('订单不存在');
        if($order->member_id != $this->request->memberId){
            return $this->error('订单不存在');
        }
        if($order->status != 3) return $this->error ('订单状态不正确');
        $order->status = 8;
        $order->edit_time = date('Y-m-d H:i:s');
        $order->save();
        return $this->success('确定成功');
    }
}

